//
//  XGL_PersonalViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/13.
//

import UIKit

class XGL_PersonalViewController: UIViewController,CustomNavgationBar {
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var personalView: XGL_PersonalHomePageView!
    private var userId: String = ""
    private var treeId: String?
    private var userData: UserFollowAndFansNumData?
    private var commentInfor: CompleteInfor?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "My  Account")
        self.hudView.hudView.startAnimation()
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.bottom.equalTo(-PanTabbarH)
            make.top.equalTo(PanNavibarH)
        }
        self.getuserDataRequest()
        
        XGL_Notice.default.addObserver(self, selector: #selector(self.loginNoticeAction), name: XGL_Notification.login.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.publishNoticeAction), name: XGL_Notification.publish.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.addBlack.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.deleteBlack.notificationName, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
        
        self.getFollowFansNumerRequest()
    }
}

extension XGL_PersonalViewController{
    
    @objc private func loginNoticeAction(){
        self.getuserDataRequest()
        self.getFollowFansNumerRequest()

        self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
        self.personalView.bottomView.likePostSegmentView.header.beginRefreshing()
    }
    
    @objc private func publishNoticeAction(){
        self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
    }
    @objc private func addblackNoticeAction(notice: Notification){
        self.personalView.bottomView.likePostSegmentView.header.beginRefreshing()
    }
    
    @objc private func personalSettingAction(){
        let pickView = XGL_PersonalPickerView()
        pickView.selectHandler = { index in
            switch index {
            case 0://edit profile
                let vc = XGL_EditProfileViewController()
                vc.id = self.treeId
                vc.handler = {
                    self.getuserDataRequest()
                }
                self.navigationController?.pushViewController(vc)
                break
            case 1: //blacklist
                let vc = XGL_Bla0klistPageViewController()
                self.navigationController?.pushViewController(vc)
                break
            case 2://terms of use
                let vc = XGL_CustomWebViewController()
                vc.navTitle = "Terms of Use"
                vc.url = Terms
                self.navigationController?.pushViewController(vc)
                break
            case 3://privacy policy
                let vc = XGL_CustomWebViewController()
                vc.navTitle = "Privacy Policy"
                vc.url = PrivacyPolicy
                self.navigationController?.pushViewController(vc)
                break
            case 4://version
                break
            case 5://delete account
                guard let window = UIApplication.shared.currentWindow else { return }
                let alertView = PersonalDeleteAlertView()
                alertView.showAlertView {
                    
                }
                window.addSubview(alertView)
                alertView.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                break
            case 6://logout
                let actionController = UIAlertController(title: "Warm reminder", message: "Logout or not ？", preferredStyle: .alert)
                let action3 = UIAlertAction(title: "Sure", style: .default) { _ in
                    let infor = XGL_userDataCacheManager.shared.token
                    infor.token = ""
                    XGL_userDataCacheManager.shared.saveInfor(inforData: infor)
                    if let window = UIApplication.shared.currentWindow {
                        window.rootViewController = loginNaviController
                    }
                }
                let action2 = UIAlertAction(title: "Cancel", style: .cancel)
                actionController.addAction(action2)
                actionController.addAction(action3)
                self.present(actionController, animated: true)
                break
            default:
                break
            }
        }
        self.view.addSubview(pickView)
        pickView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension XGL_PersonalViewController{
    private func handleruserData(){
        if let infor = self.commentInfor {
            self.personalView.inforView.nameText.text = infor.data1
            self.personalView.inforView.headerView.loadImageWithUrl(infor.data2)
            self.personalView.inforView.idText.text = "ID:\((infor.userId % 2000000000).description)"
            if infor.data3 == 0{
                self.personalView.inforView.genderIconView.image = imageWithName("icon_xgl_user_female")
            }else{
                self.personalView.inforView.genderIconView.image = imageWithName("icon_xgl_user_male")
            }
            self.personalView.gamesView.games = infor.data4.components(separatedBy: ",").filter({$0.isEmpty == false})
            self.userId = infor.userId.description
            self.treeId = infor.id
            self.getMyPublishVideoDatasRequest()
            
            XGL_userDataManager.share.userId = infor.userId.description
            XGL_userDataManager.share.userHeader = infor.data2
            XGL_userDataManager.share.userName = infor.data1
            
            self.getRecievedGiftsRequest(userId: infor.userId.description)
        }else if let infor = self.userData{
            self.personalView.inforView.nameText.text = infor.nickname
            self.personalView.inforView.headerView.loadImageWithUrl(infor.header)
            self.personalView.inforView.idText.text = "ID:\((infor.id % 2000000000).description)"
            if infor.gender == 0{
                self.personalView.inforView.genderIconView.image = imageWithName("icon_xgl_user_female")
            }else{
                self.personalView.inforView.genderIconView.image = imageWithName("icon_xgl_user_male")
            }
            self.personalView.gamesView.games = []
            self.userId = infor.id.description

            self.getMyPublishVideoDatasRequest()
            
            XGL_userDataManager.share.userId = infor.id.description
            XGL_userDataManager.share.userHeader = infor.header
            XGL_userDataManager.share.userName = infor.nickname
            self.getRecievedGiftsRequest(userId: infor.id.description)
        }
    }
}

extension XGL_PersonalViewController{
    private func getuserDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CompleteInfor>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PersonalInfor)) { result in
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    self.commentInfor = result
                    self.handleruserData()
                }
                break
            default:
                break
            }
        }
    }
    
    private func getFollowFansNumerRequest(){
        PanRequestManager<XGL_RequestBaseResponse<UserFollowAndFansNumData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .FollowsAndFansNum)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.userData = data
                    self.handleruserData()
                    self.personalView.inforView.fansItem.title = data.followerNumber.description
                    self.personalView.inforView.followItem.title = data.followingNumber.description
                }
                break
            default:
                break
            }
        }
    }
    
    private func getRecievedGiftsRequest(userId: String){
        PanRequestManager<XGL_RequestBaseResponse<GiftData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .RecievedGifts(userId: userId))) { result in
            switch result{
            case .success(let response):
                if let datas = response.resultDatas {
                    self.personalView.inforView.giftsItem.title = datas.map({$0.num}).reduce(0, +).description
                }
                break
            default:
                break
            }
        }
    }
    
    private func getMyPublishVideoDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: self.userId, page: self.personalView.bottomView.myPostSegmentView.pageIndex, size: 20, data1: "2", pid: nil, data5: nil))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.personalView.bottomView.myPostSegmentView.header.isRefreshing{
                        self.personalView.bottomView.myPostSegmentView.videosData = model.data
                        self.personalView.bottomView.myPostSegmentView.header.endRefreshing()
                        self.personalView.bottomView.myPostSegmentView.footer.resetNoMoreData()
                    }else if self.personalView.bottomView.myPostSegmentView.footer.isRefreshing{
                        self.personalView.bottomView.myPostSegmentView.videosData.append(contentsOf: model.data)
                        self.personalView.bottomView.myPostSegmentView.footer.endRefreshing()
                    }else{
                        self.personalView.bottomView.myPostSegmentView.videosData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.personalView.bottomView.myPostSegmentView.footer.endRefreshingWithNoMoreData()
                    }
                    self.personalView.bottomView.myPostSegmentView.collectionView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
    
    private func getMyThumbVideoDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetActionDatas(type: "2", page: self.personalView.bottomView.likePostSegmentView.pageIndex, size: 20))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.personalView.bottomView.likePostSegmentView.header.isRefreshing{
                        self.personalView.bottomView.likePostSegmentView.videosData = model.data
                        self.personalView.bottomView.likePostSegmentView.header.endRefreshing()
                        self.personalView.bottomView.likePostSegmentView.footer.resetNoMoreData()
                    }else if self.personalView.bottomView.likePostSegmentView.footer.isRefreshing{
                        self.personalView.bottomView.likePostSegmentView.videosData.append(contentsOf: model.data)
                        self.personalView.bottomView.likePostSegmentView.footer.endRefreshing()
                    }else{
                        self.personalView.bottomView.likePostSegmentView.videosData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.personalView.bottomView.likePostSegmentView.footer.endRefreshingWithNoMoreData()
                    }
                    self.personalView.bottomView.likePostSegmentView.collectionView.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
    
    private func deleteAccountRequest(){
        
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .DeleteAccount)) { result in
            switch result{
            case .success(let response):
                let infor = XGL_userDataCacheManager.shared.token
                infor.token = ""
                XGL_userDataCacheManager.shared.saveInfor(inforData: infor)
                self.present(loginNaviController, animated: true, completion: nil)
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalViewController: PanSegmentViewDelegate{
    func refresh(view: MXCommonModule.PanSegmentView) {
        if view == self.personalView.bottomView.myPostSegmentView{
            self.personalView.bottomView.myPostSegmentView.pageIndex = 1
            self.getMyPublishVideoDatasRequest()
        }else if view == self.personalView.bottomView.likePostSegmentView{
            self.personalView.bottomView.likePostSegmentView.pageIndex = 1
            self.getMyThumbVideoDatasRequest()
        }
    }
    
    func getMore(view: MXCommonModule.PanSegmentView) {
        if view == self.personalView.bottomView.myPostSegmentView{
            self.getMyPublishVideoDatasRequest()
        }else if view == self.personalView.bottomView.likePostSegmentView{
            self.getMyThumbVideoDatasRequest()
        }
    }
    
    func didSelectRow(view: MXCommonModule.PanSegmentView, section: NSInteger, index: NSInteger) {
        if view == self.personalView.bottomView.myPostSegmentView{
            let model = self.personalView.bottomView.myPostSegmentView.videosData[index]
            if model.data4 == "1"{
                let vc = XGL_PersonalImageDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }else{
                let vc = XGL_PersonalVideoDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }
           
        }else if view == self.personalView.bottomView.likePostSegmentView{
            let model = self.personalView.bottomView.likePostSegmentView.videosData[index]
            if model.data4 == "1"{
                let vc = XGL_PersonalImageDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }else{
                let vc = XGL_PersonalVideoDetailViewController()
                vc.detailData = model
                vc.handler = {
                    self.personalView.bottomView.myPostSegmentView.header.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func selectMoreAction(view: MXCommonModule.PanSegmentView, section: NSInteger) {
        
    }
    
    
}

extension XGL_PersonalViewController: PersonalBottomDelegate{
    func didSelectedSegmentView(segmentView: PanSegmentView) {
        if segmentView == self.personalView.bottomView.myPostSegmentView{
            self.getMyPublishVideoDatasRequest()
        }else if segmentView == self.personalView.bottomView.likePostSegmentView{
            self.getMyThumbVideoDatasRequest()
        }
    }
}

extension XGL_PersonalViewController: PersonalDelegate{
    func userFans() {
        let vc = XGL_FansPageViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    func userFollow() {
        let vc = XGL_FollowersPageViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    func userGifts() {
        let vc = XGL_PersonalReceivedGiftsViewController()
        vc.userId = self.userId
        self.navigationController?.pushViewController(vc)
    }
    
    func store() {
        let vc = XGL_PersonalRechargeViewController()
        self.navigationController?.pushViewController(vc)
    }
    
}

extension XGL_PersonalViewController{
    private func createXglView(){
        self.personalView = XGL_PersonalHomePageView().then({ make in
            make.delegate = self
            make.bottomView.delegate = self
            make.bottomView.myPostSegmentView.delegate = self
            make.bottomView.likePostSegmentView.delegate = self
        })
        self.view.addSubview(self.personalView)
        self.personalView.snp.makeConstraints { make in
            make.centerX.width.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 32.0)
            make.text = title
        }
        let settingItem = UIButton().then { make in
            make.setImage(imageWithName("icon_xgl_personal_setting"), for: .normal)
            make.addTarget(self, action: #selector(self.personalSettingAction), for: .touchUpInside)
        }
        navView.addSubview(titleView)
        navView.addSubview(settingItem)
        self.view.addSubview(navView)
        
        titleView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalTo(15.0)
        }
        settingItem.snp.makeConstraints { make in
            make.centerY.equalTo(titleView)
            make.width.height.equalTo(24.0)
            make.right.equalTo(-13.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
